package com.lc.stock.module.excel.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.collection.CollUtil;
import com.lc.stock.module.selectstockresult.dao.SelectStockResultDao;
import com.lc.stock.module.selectstockresult.domain.SelectStockResult;
import com.lc.stock.module.selectstockresult.domain.SelectStockResultDetails;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lichen
 * @description 导出筛选的股票信息
 * @menu
 * @date 2023/2/7 9:35
 */
@Slf4j
@Service
public class ExportSelectStockService {

    @Autowired
    private SelectStockResultDao selectStockResultDao;

    public void export() throws IOException {
        List<SelectStockResult> selectStockResultList = selectStockResultDao.findAll();
        if(CollUtil.isEmpty(selectStockResultList)){
            log.error("筛选的股票数据为空，不能导出");
            return;
        }

        List<Map<String, Object>> exportList = new ArrayList<Map<String, Object>>();

        for (SelectStockResult selectStockResult : selectStockResultList) {
            HashMap<String, Object> map = new HashMap<>();
            ExportParams params = new ExportParams();
            params.setTitle("筛选股票信息");
            params.setSheetName(selectStockResult.getSelectStockDate());
            map.put("title",params);
            map.put("entity",SelectStockResultDetails.class);
            map.put("data",selectStockResult.getList());
            exportList.add(map);
        }
        Workbook workbook = ExcelExportUtil.exportExcel(exportList, ExcelType.HSSF);
        // 指定写出的文件
        String projectPath = System.getProperty("user.dir");
        String path = projectPath + "/" + "result.xlsx";
        FileOutputStream outputStream = new FileOutputStream(path);
        workbook.write(outputStream);
    }

}
